package com.android.nurse;

import java.util.ArrayList;
import java.util.Collections;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class QuestionsScreen extends CommonActivity {

	private TextView text1, text2;
	private static TextView tvQuestion;
	private ImageView imgNurse;
	private LinearLayout textLayout;
	private Button btnYes, btnNo;
	Animation a;
	int width, height;
	// list question from file json
	private ArrayList<Question> listQuestion = new ArrayList<Question>();
	private ArrayList<Integer> tmpQuestion = new ArrayList<Integer>();
	// list random question
	private static ArrayList<Question> mQuestions = new ArrayList<Question>();

	public static final String PREFS_NAME = "MyPrefsFile";
	public static final String TYPE_NURSE = "NAME_TYPE_NURSE";
	public static final String ID_NURSE = "ID_NURSE";
	public static final String TIRED_POINT = "TIRED_POINT";
	private static int current = 0;
	// total match with data question
	private static int totalMatch = 0;
	// total point interest user play match with data
	private static int totalInterestPoint = 0;
	// total point energy user play match with data
	private static int totalEnergyPoint = 0;
	// total point tired user play match with data
	private static int totalTiredPoint = 0;
	// total point tired be set to data
	private static int sumTiredPoint = 0;
	// content of file json
	private String jsonQuestion;
	private NurseType nurse;
	private Question q;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		width = display.getWidth();
		Log.d("chieu rong man hinh", ""+width);
		if(width > 500){
			setContentView(R.layout.questions_big);
		} else {
		setContentView(R.layout.questions);
		}
		height = display.getHeight();
		
		/* initt list quest tion */
		if (mQuestions.size() <= 0) {
			jsonQuestion = readFile(getApplicationContext(),
					"Data/questions.json");
			if (listQuestion.isEmpty()) {
				try {
					parserJsonQuestion(jsonQuestion);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.print("questions.json error!");
					e.printStackTrace();
				}
			}
			getRanDomQuestion();
		}
		q = mQuestions.get(current++);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, height / 2);
		LinearLayout layout1 = (LinearLayout) findViewById(R.id.layout1);
		layout1.setLayoutParams(params);
		LinearLayout layout2 = (LinearLayout) findViewById(R.id.layout2);
		layout2.setLayoutParams(params);
		LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
				getResources()
						.getDimensionPixelSize(R.dimen.width_img_question),
				getResources()
						.getDimensionPixelSize(R.dimen.heigh_img_question));
		params1.setMargins(0, 0, getResources().getDimensionPixelSize(
				R.dimen.mergin_button), getResources().getDimensionPixelSize(R.dimen.mergin_yes_no));
		LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, getResources().getDimensionPixelSize(
						R.dimen.header_question));
		params2.setMargins(getResources().getDimensionPixelSize(
				R.dimen.mergin_button), 0, getResources()
				.getDimensionPixelSize(R.dimen.mergin_button), 0);
		LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
				getResources().getDimensionPixelSize(R.dimen.width_yes_no),
				getResources().getDimensionPixelSize(R.dimen.heigh_yes_no));
		params3.setMargins(0, getResources().getDimensionPixelSize(
				R.dimen.margin_right), getResources().getDimensionPixelSize(
				R.dimen.mergin_yes_no), 0);
		LinearLayout.LayoutParams params4 = new LinearLayout.LayoutParams(
				getResources().getDimensionPixelSize(R.dimen.width_yes_no),
				getResources().getDimensionPixelSize(R.dimen.heigh_yes_no));
		params4.setMargins(0, getResources().getDimensionPixelSize(
				R.dimen.margin_right), 0, 0);

		textLayout = (LinearLayout) findViewById(R.id.textLayout);
		text1 = (TextView) findViewById(R.id.tvText1);
		text2 = (TextView) findViewById(R.id.tvText2);
		tvQuestion = (TextView) findViewById(R.id.tvQuestion);
		imgNurse = (ImageView) findViewById(R.id.imgNurse);
		btnYes = (Button) findViewById(R.id.btnYes);
		btnNo = (Button) findViewById(R.id.btnNo);
		myThread.start();

		text1.setTextSize(getResources().getDimensionPixelSize(
				R.dimen.font_text_Question));
		text2.setTextSize(getResources().getDimensionPixelSize(
				R.dimen.font_text_Question));
		tvQuestion.setTextSize(getResources().getDimensionPixelSize(
				R.dimen.font_text_Question));
		tvQuestion.setText(q.getQuestion());
		text1.setText("質問 "+current);
		text2.setText(current + "/10");
		textLayout.setLayoutParams(params2);
		if(width < 500){
		imgNurse.setLayoutParams(params1);
		btnYes.setLayoutParams(params3);
		btnNo.setLayoutParams(params4);
		}
		btnYes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sumTiredPoint += q.getTiredPoint();
				if (current < 10) {
					if (q.getJudg() == getYesAnswer()) {
						totalMatch++;
						totalInterestPoint += q.getInterestPoint();
						totalEnergyPoint += q.getEnergyPoint();
						totalTiredPoint += q.getTiredPoint();
					}
				} else {
					if (q.getJudg() == getYesAnswer()) {
						totalMatch++;
						totalInterestPoint += q.getInterestPoint();
						totalEnergyPoint += q.getEnergyPoint();
						totalTiredPoint += q.getTiredPoint();
					} else {						
						totalInterestPoint -= q.getInterestPoint();
						totalEnergyPoint -= q.getEnergyPoint();						
					}
				}
				// TODO Auto-generated method stub
				if (current < 10) {
					Intent i = new Intent(getApplicationContext(),
							QuestionsScreen.class);
					customeActivity(i);
				} else {
					nurse = getNurseType(getIdTypeMaster(totalInterestPoint,
							totalEnergyPoint));
					sendData();
					resetData();
					Intent i = new Intent(getApplicationContext(), Result.class);
					customeActivity(i);
				}
			}
		});
		btnNo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sumTiredPoint += q.getTiredPoint();
//				if (q.getJudg() == getNoAnswer()) {
//					totalMatch++;
//					totalInterestPoint += q.getInterestPoint();
//					totalEnergyPoint += q.getEnergyPoint();
//					totalTiredPoint += q.getTiredPoint();
//				}
				if (current < 10) {
					if (q.getJudg() == getNoAnswer()) {
						totalMatch++;
						totalInterestPoint += q.getInterestPoint();
						totalEnergyPoint += q.getEnergyPoint();
						totalTiredPoint += q.getTiredPoint();
					}
				} else {
					if (q.getJudg() == getNoAnswer()) {
						totalMatch++;
						totalInterestPoint += q.getInterestPoint();
						totalEnergyPoint += q.getEnergyPoint();
						totalTiredPoint += q.getTiredPoint();
					} else {						
						totalInterestPoint -= q.getInterestPoint();
						totalEnergyPoint -= q.getEnergyPoint();						
					}
				}
				if (current < 10) {
					// TODO Auto-generated method stub
					Intent i = new Intent(getApplicationContext(),
							QuestionsScreen.class);
					customeActivity(i);
				} else {
					nurse = getNurseType(getIdTypeMaster(totalInterestPoint,
							totalEnergyPoint));
					sendData();
					resetData();
					Intent i = new Intent(getApplicationContext(), Result.class);
					customeActivity(i);
				}
			}
		});
	}

	/**
	 * Analysis file json
	 * 
	 * @param json
	 *            : content of Json file
	 * @throws Exception
	 */
	public void parserJsonQuestion(String json) throws Exception {
		JSONObject jObject = new JSONObject(json);
		for (int number = 1; number <= 10; number++) {
			JSONArray noArray = jObject.getJSONArray("no" + number);
			for (int i = 0; i < noArray.length(); i++) {
				Question Q = new Question();
				JSONObject noQuestion = noArray.getJSONObject(i);
				Q.setID(noQuestion.getInt("id"));
				Q.setQuestion(noQuestion.getString("question"));
				Q.setJudg(noQuestion.getInt("judg"));
				Q.setQuestionCategory(noQuestion.getInt("question_category"));
				Q.setTypeCategory(noQuestion.getInt("type_category"));
				Q.setInterestPoint(noQuestion.getInt("interest_point"));
				Q.setEnergyPoint(noQuestion.getInt("energy_point"));
				Q.setTiredPoint(noQuestion.getInt("tired_point"));
				listQuestion.add(Q);
			}
		}
	}

	/**
	 * select random 10 question from list question
	 */
	public void getRanDomQuestion() {
		int count = 0;
		for (int j = 0; j < 4; j++) {
			for (int i = count; i < count + 10; i++) {
				tmpQuestion.add(i);
			}

			Collections.shuffle(tmpQuestion);
			mQuestions.add(listQuestion.get(tmpQuestion.get(0)));
			mQuestions.add(listQuestion.get(tmpQuestion.get(1)));
			tmpQuestion.clear();
			count += 10;
		}

		for (int j = 0; j < 2; j++) {
			for (int i = count; i < count + 4; i++) {
				tmpQuestion.add(i);

			}
			Collections.shuffle(tmpQuestion);
			mQuestions.add(listQuestion.get(tmpQuestion.get(0)));
			tmpQuestion.clear();
			count += 4;
		}

	}

	/**
	 * judge type of nurse
	 * 
	 * @param totalInterest
	 *            : total point interest
	 * @param totalEnergy
	 *            : total point energy
	 * @return ID of type nurse
	 */
	public int getIdTypeMaster(int totalInterest, int totalEnergy) {
		if (totalMatch <= 2) {
			return Constant.TETSUJIN_NURSE_ID;
		}
		if (totalInterest > 0) {
			if (totalEnergy > 0) {
				return Constant.BAKUHATSU_NURSE_ID;
			} else {
				return Constant.YASAGURE_NURSE_ID;
			}
		} else {
			if (totalEnergy > 0) {
				return Constant.TAMEKOMI_NURSE_ID;
			} else {
				return Constant.MOETSUKI_NURSE_ID;
			}
		}
	}

	/**
	 * caculate tired point of nurse
	 * 
	 * @param A
	 *            : total tired point user play app
	 * @param B
	 *            : total tired point be set in data question with questions
	 *            displayed on screen
	 * @param constant
	 *            : field "tired_coefficient" in file configs.json
	 * @return
	 */
	public int getTiredPoint(int A, int B, double constant) {
		int point = (int) ((1 - Math.pow((1 - (float) A / B), constant)) * 100);
		return point;
	}

	/*
	 * save data into SharedPreferences
	 */
	public void sendData() {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor edit = settings.edit();
		edit.putString(TYPE_NURSE, nurse.getName());
		edit.putInt(ID_NURSE, getIdTypeMaster(totalInterestPoint,
				totalEnergyPoint));
		edit.putInt(TIRED_POINT, getTiredPoint(totalTiredPoint, sumTiredPoint,
				getTiredCoefficient()));
		edit.commit();
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
//		super.onBackPressed();
//		resetData();
		return;
	}

	public static void resetData() {
		mQuestions.clear();
		sumTiredPoint = 0;
		current = 0;
		totalEnergyPoint = 0;
		totalInterestPoint = 0;
		totalMatch = 0;
		totalTiredPoint = 0;
	}
	
	private Thread myThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			btnYes.setClickable(false);
			btnNo.setClickable(false);
			synchronized (this) {
				try {
					wait(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			btnYes.setClickable(true);
			btnNo.setClickable(true);
		}
	});

}
